<?php

namespace app\admin\model\facrm\qywx;


use EasyWeChat\Factory;
use fast\Random;
use think\Db;
use think\Exception;
use think\Model;

class Contacts extends Model
{


    // 表名
    protected $name = 'facrm_qywx_contacts';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    public $error = "";

    // 追加属性
    protected $append = [
        'status_text',
        'create_time_text',
        'update_time_text'
    ];

	public function hasContacts($row, $config){
		if (is_string($row)){
            //不存在就去同步企业微信
            $appc = Factory::work([
                'corp_id' => $config['corp_id'],
                'secret' => $config['customer_secret'], // 客户的 secret
            ]);
            $external_c = $appc->external_contact->get($row);
            if (!$external_c || $external_c['errcode'] != '0' || !$external_c['external_contact']) {
                $this->error = (__("获取信息失败"));
				return false;
            }
            $external_contact = $external_c['external_contact'];
            $follow_user = $external_c['follow_user'];
        }else{
            $external_contact = $row['external_contact'];
            $follow_user = $row['follow_info'];
        }

        $external_userid=$external_contact['external_userid'];
        $qywxContacts = $this->where('external_userid', $external_userid)->find();

		return ['contact' => $qywxContacts, 'external' => $external_contact, 'follow_user' => $follow_user];
	}

    /**
     * 获取本地微信客户
     * @param $row $external_userid or external
     * @param $config
     * @param array $extend
     * @return Contacts|array|bool|false|\PDOStatement|string|Model
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getContacts($row, $config, $extend = array(), $createCustomer = true)
    {
        $qywx = $this->hasContacts($row, $config);
		$qywxContacts = $qywx['contact'];
		$follow_user = $qywx['follow_user'];
		$external_contact = $qywx['external'];
		$external_userid = $external_contact['external_userid'];

        if (!$qywxContacts) {
            //插入本地数据
            $external_contact['corp_id'] = $config['corp_id'];
            $qywxContacts = $this->allowField(true)->create(array_merge($external_contact, ['follow_user' => json_encode($follow_user)]), true);

			// 创建客户信息
			if ($createCustomer){
				Db::startTrans();
				try{

					$customer_id = 0;
					$customer_name = isset($external_contact['corp_full_name'])?$external_contact['corp_full_name']:$external_contact['name']."@".$this->buildShort($external_contact['external_userid']);//如果不是企业用户
					$remark_mobiles = isset($follow_user[0]['remark_mobiles'][0])?$follow_user[0]['remark_mobiles'][0]:'';

					//获取crm配置
					$addon_config = get_addon_config('facrm');
					$customerModel = new \app\admin\model\facrm\Customer();
					$contactModel = new \app\admin\model\facrm\customer\Contacts();

					// 微信用户表中查询相关用户
					$customer_contact = $contactModel->alias('cc')->join('wechat_user u', 'cc.uid = u.uid')->where('u.unionid', '=', $external_contact['unionid'])->field('cc.customer_id,cc.id')->find();
					$customer_id = $customer_contact['customer_id'];
					$customer_contact_id = $customer_contact['id'];
					if (!$customer_contact){
						switch ($addon_config['unique']){
							case 'name':
								$customer_id = $customerModel->where('name', $customer_name)->value('id');
								break;
							case 'mobile':
								if ($remark_mobiles){
									$customer_id = $customerModel->where('mobile', $remark_mobiles)->value('id');
								}
								break;
						}
					}
					//如果本地数据库不存在客户 就添加
					if (!$customer_id){
						//customer表插入和判断规格
						//如果有corp_full_name把该信息以公司名称存储，如果没有就以备注手机为条件存储
						$tags = "";
						$tags_arr = array (__($external_contact['type'] == 1?"微信用户":"企业微信"));
						if (isset($follow_user[0]['tags']) && $follow_user[0]['tags']){
							foreach ($follow_user[0]['tags'] as $tag){
								if ($tags_arr && in_array($tag['tag_name'], $tags_arr)) continue;
								$tags_arr[] = $tag['tag_name'];
							}
							$tags = implode(",", $tags_arr);
						}
						//添加未本地客户 默认为第一个跟进人
						$add_customer = [
							'name' => $customer_name,
							'mobile' => $remark_mobiles,
							'telephone' => isset($follow_user[0]['remark_mobiles'][1])?$follow_user[0]['remark_mobiles'][1]:'',
							//用电话记录第二个联系方式
							'source' => $config['source'],
							'tags' => $tags,
							'create_user_id' => $extend['admin_id'],
							'owner_user_id' => $extend['admin_id'],
							'next_time' => time(),
							//提醒跟进
							'follow_time' => time(),
							'collect_time' => time(),
							'remark' => (isset($follow_user[0]['remark'])?$follow_user[0]['remark']:'')."@".__($external_contact['type'] == 1?"微信用户":"企业微信"),
						];
						$customer_id = $customerModel->add($add_customer, 0, 0, false);
						$customer_contact_id = $contactModel->where('customer_id', $customer_id)->limit(0, 1)->value('id');
					}

					$qywxContacts->customer_id = $customer_id;
					if ($customer_contact_id) $qywxContacts->customer_contact_id = $customer_contact_id;
					$qywxContacts->save();
					Db::commit();

				}catch (\Exception $e){
					Db::rollback();
				}
			}

        } else {
            //更新
            $qywxContacts->isUpdate(true)->allowField(true)
                ->update(array_merge($external_contact, ['follow_user' => json_encode($follow_user)]),
                    ['external_userid' => $external_userid], true);

        }
        return $qywxContacts;
    }


    /**
     * 客户对象
     * @return \think\model\relation\BelongsTo
     */
    public function customer()
    {
        return $this->belongsTo('\app\admin\model\facrm\Customer', 'customer_id', 'id');
    }

    /**
     * 转化成短字符
     * @param $str
     * @return string
     */
    protected function buildShort($str)
    {

        $result = sprintf("%u", crc32($str));
        $show = '';
        while ($result > 0) {
            $s = $result % 62;
            if ($s > 35) {
                $s = chr($s + 61);
            } elseif ($s > 9 && $s <= 35) {
                $s = chr($s + 55);
            }
            $show .= $s;
            $result = floor($result / 62);
        }

        return $show;

    }

    public function getStatusList()
    {
        return ['30' => __('Status 30')];
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ?: ($data['status'] ?? '');
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['create_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['update_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    public function contacts()
    {
        return $this->belongsTo('app\admin\model\facrm\customer\Contacts', 'customer_contact_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}